package com.zjq.authoritysystem.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zjq.authoritysystem.vo.result.Result;
import com.zjq.authoritysystem.vo.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Kimiaaaaa
 * @className CustomerAccessDeniedHandler
 * @Description 认证用户访问（无权限资源时）拒绝处理器
 * @date 2023-09-19 15:36
 */
@Slf4j
@Component
public class CustomerAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        log.info("-----------认证用访问拒绝处理器启动");

        response.setContentType("application/json;charset=utf-8");


        ServletOutputStream outputStream = response.getOutputStream();

        String result = JSON.toJSONString(Result.Error(ResultCode.NO_AUTH.getCode(), "无权限访问，请联系管理员"), SerializerFeature.DisableCircularReferenceDetect);
        log.info("异常信息：" + result);

        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();

        log.info("-----------认证用访问拒绝处理器结束");
    }
}
